package com.xjscrm.console.chat.core.impl;

import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.recv.RGetDeviceInfoMsg;
import com.xjscrm.console.chat.frame.send.SGetDeviceInfoResultMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.dto.WwDeviceDTO;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/12 09:41
 */
@Component
@Slf4j
public class ChatGetDeviceInfoMsgHandler extends ChatBaseMsgHandler<RGetDeviceInfoMsg> {

    @Autowired
    private WwDeviceService deviceService;

    @Override
    public SResultMsg doHandle(RGetDeviceInfoMsg content, ChannelHandlerContext ctx) {

        SGetDeviceInfoResultMsg getDeviceInfoResultMsg = new SGetDeviceInfoResultMsg();

        try {
            Long merId = content.getMerId();
            Long deviceUniqueId = content.getDeviceUniqueId();

            WwDevice byId = deviceService.getById(merId, deviceUniqueId);
            if (Objects.isNull(byId)) {
                throw new BusinessException("机器人设备未找到");
            }
            WwDeviceDTO wwDeviceDTO = new WwDeviceDTO();
            BeanUtils.copyProperties(byId, wwDeviceDTO);

            getDeviceInfoResultMsg.setDevice(wwDeviceDTO);
        } catch (Exception e) {
            log.error("获取机器人详情失败", e);
            throw new BusinessException("获取机器人详情失败");
        }
        return getDeviceInfoResultMsg;
    }

    @Override
    public boolean checkMsg(RGetDeviceInfoMsg baseMsg) {
        return super.checkMsg(baseMsg) || !Objects.nonNull(baseMsg.getDeviceUniqueId());
    }

    @Override
    public Class<RGetDeviceInfoMsg> msgClass() {
        return RGetDeviceInfoMsg.class;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_get_device_info;
    }
}
